<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        table-layout="auto"
      >
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="username" label="用户名" min-width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="nikeName" label="昵称" min-width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="idNumber" label="身份证号" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="role" label="角色" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag 
              :type="row.role === 'ADMIN' ? 'danger' : 'info'"
              effect="light"
              size="small"
            >
              {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" link @click="handleResetPwd(row)">重置密码</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nikeName">
          <el-input v-model="userForm.nikeName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="userForm.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, addUser, updateUser, deleteUser, resetPassword } from '@/api/user'

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username,
      phone: searchForm.phone
    }
    const res = await getUserList(params)
    if (res.success) {
      tableData.value = res.data.list
      total.value = res.data.total
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败：', error)
    // 只有在拦截器没有显示错误时才显示
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '获取用户列表失败')
      } else {
        ElMessage.error('获取用户列表失败，请稍后重试')
      }
    }
  } finally {
    loading.value = false
  }
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)

// 用户表单
const userForm = reactive({
  username: '',
  nikeName: '',
  email: '',
  phone: '',
  idNumber: '',
  balans: 0,
  role: '',
  password: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nikeName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.phone = ''
  currentPage.value = 1
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(userForm, {
    username: '',
    nikeName: '',
    email: '',
    phone: '',
    idNumber: '',
    balans: 0,
    role: 'USER',
    password: ''
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    nikeName: row.nikeName,
    email: row.email,
    phone: row.phone,
    idNumber: row.idNumber,
    balans: row.balans,
    role: row.role,
    password: undefined  // 设置为undefined，这样在提交时不会包含密码字段
  })
  dialogVisible.value = true
}

// 重置密码
const handleResetPwd = async (row) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await resetPassword(row.id)
    if (res.success) {
      ElMessage.success('密码重置成功')
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('重置密码失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '重置密码失败')
      } else {
        ElMessage.error('重置密码失败，请稍后重试')
      }
    }
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteUser(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchUserList()
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '删除用户失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('删除用户失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '删除用户失败')
      } else {
        ElMessage.error('删除用户失败，请稍后重试')
      }
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    let res;
    if (dialogType.value === 'add') {
      res = await addUser(userForm)
      if (res.success) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchUserList()
      } else if (!res._showError) {
        // 只有在拦截器没有显示错误时才显示
        ElMessage.error(res.msg || '添加用户失败')
      }
    } else {
      res = await updateUser(userForm)
      if (res.success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchUserList()
      } else if (!res._showError) {
        // 只有在拦截器没有显示错误时才显示
        ElMessage.error(res.msg || '更新用户失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('提交表单失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '提交失败')
      } else {
        ElMessage.error('提交失败，请检查表单内容')
      }
    }
  }
}

// 页面大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? '' : 'row-stripe'
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-container {
  width: 100%;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 15px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 15px 20px;
  box-sizing: border-box;
  width: 100%;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.row-stripe {
  background-color: #fafafa;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 